'use strict';

const Service = require('egg').Service;

class QuestionService extends Service {
  // 获取题目列表
  async findAll(options = {}) {
    const { ctx } = this;
    const { category_id, page = 1, pageSize = 5 } = options;
    
    const where = {};
    if (category_id) {
      where.category_id = category_id;
    }

    const offset = (page - 1) * pageSize;
    const limit = parseInt(pageSize);

    const { count, rows } = await ctx.model.Question.findAndCountAll({
      where,
      include: [
        {
          model: ctx.model.QuestionCategory,
          as: 'category',
          attributes: ['category_id', 'category_name'],
        },
        {
          model: ctx.model.QuestionAnswer,
          as: 'answers',
          attributes: ['answer_id', 'answer_content'],
        }
      ],
      order: [['created_at', 'DESC']],
      offset,
      limit,
    });

    return {
      data: rows,
      pagination: {
        current: page,
        pageSize: pageSize,
        total: count,
        pages: Math.ceil(count / pageSize)
      }
    };
  }

  // 根据ID获取题目
  async findById(id) {
    const { ctx } = this;
    return await ctx.model.Question.findByPk(id, {
      include: [
        {
          model: ctx.model.QuestionCategory,
          as: 'category',
          attributes: ['category_id', 'category_name'],
        },
        {
          model: ctx.model.QuestionAnswer,
          as: 'answers',
          attributes: ['answer_id', 'answer_content'],
        }
      ],
    });
  }

  // 创建题目
  async create(data) {
    const { ctx } = this;
    return await ctx.model.Question.create(data);
  }

  // 更新题目
  async update(id, data) {
    const { ctx } = this;
    const question = await ctx.model.Question.findByPk(id);
    if (question) {
      await question.update(data);
      return question;
    }
    return null;
  }

  // 删除题目
  async delete(id) {
    const { ctx } = this;
    const question = await ctx.model.Question.findByPk(id);
    if (question) {
      await question.destroy();
      return true;
    }
    return false;
  }
}

module.exports = QuestionService;
